package com.west_traveler.tiyutoutiao.fragment.main_fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.west_traveler.tiyutoutiao.R;
import com.west_traveler.tiyutoutiao.adapter.NewsViewPagerAdapter;
import com.west_traveler.tiyutoutiao.application.BaseApplication;
import com.west_traveler.tiyutoutiao.databinding.FragmentNewsFrgBinding;
import com.west_traveler.tiyutoutiao.entity.title_entity.ChannelsBean;
import com.west_traveler.tiyutoutiao.entity.title_entity.Title;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsFrg extends Fragment implements Callback<Title> {

    private FragmentNewsFrgBinding binding;
    private List<ChannelsBean> listTitle;
    private String[] data_version;
    private int[] channel_id;

    public NewsFrg() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        data_version = getActivity().getApplicationContext().getResources().getStringArray(R.array.data_version);
        channel_id = getActivity().getApplicationContext().getResources().getIntArray(R.array.channel_id);
        binding = DataBindingUtil.inflate(LayoutInflater.from(container.getContext()), R.layout.fragment_news_frg, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ((BaseApplication) getActivity().getApplication()).getService().getTitle().enqueue(this);
    }

    @Override
    public void onResponse(Call<Title> call, Response<Title> response) {
        listTitle = response.body().getData().getChannels();
        NewsViewPagerAdapter adapter = new NewsViewPagerAdapter(getFragmentManager(), listTitle, channel_id, data_version);
        binding.vpNews.setAdapter(adapter);
        binding.tab.setupWithViewPager(binding.vpNews);
    }

    @Override
    public void onFailure(Call<Title> call, Throwable t) {
        t.getStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
